<?php 

namespace app\bee\controller;
use think\Controller;
use think\Cache;
use \DOMDocument;
use \DateTime;

class Walmart extends BeeController {
  public $default_url = 'https://www.walmart.com/';
  public $default_api_base_url = 'http://api.walmartlabs.com';
  public $api_base_url = "http://api.walmartlabs.com/v1/search";
  public $api_key = 'y862bhat5p4dth7qt3faxjm8';
  
  public function index() {
    echo 'walmart';
  }
  /**
   * @input string keywords, sepearted by space
   */
  public function getProductsByAPI($keywords, $opt = array()) {
    if (!isset($keywords)) { 
      return array(
        'msg' => '$keywords is not set yet.',
        'data' => null
      );
    }
    $request_data = [
      'query' => $keywords,
      'format' => 'json',
      'apiKey' => $this->api_key,
      'numItems' => 25,
      'start' => 1
    ];
    if (isset($_GET['page'])) {
      $request_data['start'] = intval($_GET['page']) * $request_data['numItems'];
      $this->assign('page', $_GET['page']);
    } else {
      $this->assign('page', 0);
    }
    if (is_array($opt) && !empty($opt)) {
      $request_data['facet'] = 'on';
      $request_data = array_merge($request_data, $opt);
    }
    // var_dump('$opt', $opt);
    // var_dump($this->api_base_url . '?' . http_build_query($request_data));
    
    $respond = file_get_contents($this->api_base_url . '?' . http_build_query($request_data));
    $respond = mb_convert_encoding($respond, 'UTF-8',
          mb_detect_encoding($respond, 'UTF-8, ISO-8859-1', true));
    return json_decode($respond, true);
    // var_dump($products);
    // ?query=gerber&format=json&facet=on&facet.filter=brand%3AGerber&apiKey=y862bhat5p4dth7qt3faxjm8
  }
  public function getProducts($url, $type = '') {
    if (!isset($url)) { 
      return array(
        'msg' => '$url is not set yet.',
        'data' => null
      );
    }
    
    $doc = new DOMDocument();
    $product_container = 'search-result-gridview-item';
    $response = $this->request($url);
    var_dump(http_get($url));
    libxml_use_internal_errors(true);
    var_dump($response);
    die();
    $doc->loadHTML($response);
    $divs = $doc->getElementsByTagsName('div');
    
    foreach ($divs as $div) {
      if (strpos($div->getAttribute('class'), $product_container)) {
        var_dump("found");
      }
    }
    return null;
  }
}